package org.bite.lesson04;
/**
 * 用类对象做为锁对象
 *
 */
public class Demo409 {
    public static void main(String[] args) throws InterruptedException {
        // 初始化累加对象
        Counter408 counter = new Counter408();
        Counter408 counter1 = new Counter408();

        // 创建两个线程对一个变量进时累加
        Thread t1 = new Thread(() -> {
            // 5万次
            for (int i = 0; i < 50000; i++) {
                counter.increase();
            }
        });

        // 线程2
        Thread t2 = new Thread(() -> {
            // 5万次
            for (int i = 0; i < 50000; i++) {
                counter1.increase();
            }
        });

        // 启动线程
        t1.start();
        t2.start();

        // 等待线程执行完成
        t1.join();
        t2.join();

        // 查看运行结果
        System.out.println("count = " + counter.count);

    }
}

// 专门用来累的类
class Counter409 {
    // 初始值是0
    public static int count = 0;

    /**
     * 累加方法
     */
    public void increase () {

        // 只锁定代码块
        synchronized (Counter409.class) {
            count++;
        }

    }


}
